<template>
  <el-row>
    <el-col :span="12">
      <el-form ref="formRef" :model="pwdForm" :rules="rules" label-width="100px">
        <el-form-item label="原密码" prop="old_pwd">
          <el-input v-model="pwdForm.old_pwd" show-password disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input v-model="pwdForm.new_pwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="re_pwd">
          <el-input v-model="pwdForm.re_pwd" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">修改密码</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { updateEmployeePassword } from '@/api/employee'
const formRef = ref()
const pwdForm = ref({
  old_pwd: '******',
  new_pwd: '',
  re_pwd: ''
})
const checkDifferent = (rule, value, callback) => {
  // 校验新密码和原密码不能一样
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能与原密码一样'))
  } else {
    callback()
  }
}
const checkSameAsNewPwd = (rule, value, callback) => {
  // 校验确认密码必须和新密码一样
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('确认密码必须和新密码一样'))
  } else {
    callback()
  }
}
const rules = ref({
  old_pwd: [
    { min: 6, max: 15, message: '原密码长度在6-15位之间', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '新密码长度在6-15位之间', trigger: 'blur' },
    { validator: checkDifferent, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '确认密码长度在6-15位之间', trigger: 'blur' },
    { validator: checkSameAsNewPwd, trigger: 'blur' }
  ]
})
const resetForm = () => {
  //重置表单
  formRef.value.resetFields(['new_pwd', 're_pwd'])
}

const loginData = reactive({
  password: ''
})

// 监视loginData中password的变化
watch(() => loginData.password, (newPassword) => {
  // 将新的用户名赋值给pwdForm的old_pwd
  pwdForm.value.old_pwd = newPassword
})
// 提交表单的方法，用于修改密码
const submitForm = async () => {
  try {
    // 使用formRef进行表单验证
    await formRef.value.validate()
    // 验证通过后执行密码修改逻辑
    loginData.password = pwdForm.value.new_pwd
    // console.log(JSON.stringify(loginData));

    updateEmployeePassword(loginData).then(response => {
      // console.log(response)
      // 刷新原密码的值
      pwdForm.value.old_pwd = loginData.password
      formRef.value.resetFields(['new_pwd', 're_pwd'])
      ElMessage.success('修改成功')
    }).catch(error => {
      console.error(error)
    })


  } catch (error) {
    // 表单验证失败，可以在这里处理错误信息或其他逻辑
    console.error('表单验证失败', error)
    ElMessage.error('修改失败')
  }
}

</script>

<style scoped></style>